//
//  YGKShowPathController.m
//  GatherFlag
//
//  Created by CoderSUX on 16/7/7.
//  Copyright © 2016年 CoderSUX. All rights reserved.
//

#import "YGKShowPathController.h"
#import <CoreLocation/CoreLocation.h>
#import <CoreData/CoreData.h>
#import "HMDataManager.h"
#import "Flag.h"
#import "PathPoint.h"
#import "IWHttpTool.h"
#define XCodeRate 0.002871
#define YCodeRate 0.002708
NSString *const PathCellID = @"PathFlagCell";
@interface YGKShowPathController ()<CLLocationManagerDelegate>
@property(nonatomic, strong)CLLocationManager *mgr;
@property (nonatomic) NSFetchedResultsController *fetchedResultsController;
@property (nonatomic) NSFetchedResultsController *fetchedController;
@property (strong, nonatomic) NSMutableArray *result;
@property(nonatomic, strong) NSString *flagID;
@property(nonatomic, strong) NSString *states;
@end

@implementation YGKShowPathController

- (NSMutableArray *)result
{
    if (!_result) {
        _result = [NSMutableArray array];
    }
    return _result;
}

-(CLLocationManager *)mgr
{
    if (!_mgr) {
        _mgr = [[CLLocationManager alloc] init];
        _mgr.delegate = self;
        //定位精度设置为导航
        _mgr.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
        _mgr.distanceFilter = 100;
    }
    
    return _mgr;
}

- (void)addCloseButton
{
    UIButton *button = [[UIButton alloc] init];
    [button setTitle:@"关闭" forState:(UIControlStateNormal)];
    
    button.frame = CGRectMake([UIScreen mainScreen].bounds.size.width - 80, 30, 60, 30);
    button.backgroundColor = [UIColor colorWithRed:0.7 green:0.7 blue:0.7 alpha:0.3];
    [self.view addSubview:button];
    [button addTarget:self action:@selector(close) forControlEvents:UIControlEventTouchUpInside];
    
    self.tableView.contentInset = UIEdgeInsetsMake(20, 0, 0, 0);
}

- (void)close
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self pushToServer];
    
    [self addCloseButton];
    
    self.flagID = nil;
    
    [self beginLocation];
    
}

- (void)beginLocation
{
    if ([self.mgr respondsToSelector:@selector(requestAlwaysAuthorization)])
    {
        [self.mgr requestAlwaysAuthorization];
    }
    //开始定位
    [self.mgr startUpdatingLocation];
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:PathCellID];
}

#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.fetchedController.fetchedObjects.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:PathCellID forIndexPath:indexPath];
    PathPoint *path = self.fetchedController.fetchedObjects[indexPath.row];
    NSString *type = nil;
    if ([path.type isEqualToString:@"1"]) {
        type = @"收费站";
    }else if ([path.type isEqualToString:@"2"])
    {
        type = @"路径标识点";
    }else
    {
        type = @"未识别的错误类型";
    }
    cell.textLabel.text = [NSString stringWithFormat:@"经过标识点的id为: %@ 坐标:%f %f 类型为:%@",path.flag_id,[path.y_code floatValue],[path.x_code floatValue],type];
    cell.textLabel.numberOfLines = 0;
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 88;
}
- (NSFetchedResultsController *)fetchedController {
    if (_fetchedController) return _fetchedController;
    
    NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"PathPoint"];
    
    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"x_code" ascending:YES];
    NSSortDescriptor *sort1 = [NSSortDescriptor sortDescriptorWithKey:@"y_code" ascending:YES];
    fetchRequest.sortDescriptors = @[sort,sort1];
    
    _fetchedController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:[HMDataManager sharedManager].managedObjectContext sectionNameKeyPath:nil cacheName:nil];
    
    return _fetchedController;
}
- (NSFetchedResultsController *)fetchedResultsController {
    if (_fetchedResultsController) return _fetchedResultsController;
    
    NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Flag"];
    
    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"x_code" ascending:YES];
    NSSortDescriptor *sort1 = [NSSortDescriptor sortDescriptorWithKey:@"y_code" ascending:YES];
    fetchRequest.sortDescriptors = @[sort,sort1];
    
    _fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:[HMDataManager sharedManager].managedObjectContext sectionNameKeyPath:nil cacheName:nil];
    
    return _fetchedResultsController;
}


#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    CLLocation *location = locations[0];
    float min_xcode = location.coordinate.longitude - XCodeRate;
    float max_xcode = location.coordinate.longitude + XCodeRate;
    float min_ycode = location.coordinate.latitude - YCodeRate;
    float max_ycode = location.coordinate.latitude + YCodeRate;
    
    self.fetchedResultsController.fetchRequest.predicate = [NSPredicate predicateWithFormat:@"x_code > %f AND x_code < %f AND y_code > %f AND y_code < %f", min_xcode, max_xcode, min_ycode,max_ycode];
    [self.fetchedResultsController performFetch:NULL];
    static int pathCheckCount = 0;
    
    if (self.fetchedResultsController.fetchedObjects.count > 0)
    {
        Flag *flag = self.fetchedResultsController.fetchedObjects.lastObject;
        pathCheckCount ++;
        if (self.flagID != flag.flag_id)
        {
            PathPoint *path = [NSEntityDescription insertNewObjectForEntityForName:@"PathPoint" inManagedObjectContext:[HMDataManager sharedManager].managedObjectContext];
            path.flag_id = flag.flag_id;
            path.x_code = flag.x_code;
            path.y_code = flag.y_code;
            path.type = flag.type;
            path.checkCount = [NSNumber numberWithInt:pathCheckCount];
            [[HMDataManager sharedManager] saveContext];

            pathCheckCount = 0;
//            [self.result addObject:flag];

            self.flagID = flag.flag_id;
        }else if(self.flagID == flag.flag_id)
        {
            
            pathCheckCount ++;
            if (pathCheckCount == 3) {
                PathPoint *path = [NSEntityDescription insertNewObjectForEntityForName:@"PathPoint" inManagedObjectContext:[HMDataManager sharedManager].managedObjectContext];
                path.flag_id = flag.flag_id;
                path.x_code = flag.x_code;
                path.y_code = flag.y_code;
                path.type = flag.type;
                [[HMDataManager sharedManager] saveContext];
            }

            NSLog(@"%d",pathCheckCount);
        }
        self.fetchedController.fetchRequest.predicate = nil;
        [self.fetchedController performFetch:NULL];
        [self.tableView reloadData];
    }
}

- (void)pushToServer
{
    //登录获取tocken
    //[self LoginHttpToolWithAccount:@"13671743863" password:@"1231"];
    
    [self pointReportWithTocken:@"7dde3c29-6e3a-4dd2-9406-cd135a9f39d7" pointId:@[@"1",@"2"]];

}

- (void)LoginHttpToolWithAccount:(NSString *)account password:(NSString *)pwd
{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"sign"] = [NSString stringWithFormat:@"{\"mobile\":\"%@\",\"password\":\"%@\",\"plat_form\":\"3\",\"app_version\":\"1.0\"}",account,pwd];
    NSString *url = @"http://120.76.154.75/app/api/member/login";
//    http://120.76.154.75/app/api/member/login?sign={\"mobile\":\"%@\",\"password\":\"%@\",\"plat_form\":\"3\",\"app_version\":\"1.0\"}
    [IWHttpTool postWithURL:url params:params success:^(id json)
     {
         NSDictionary *dict = json;
         NSDictionary *data = dict[@"data"];
         NSLog(@"%@", data[@"token"]);
         
     } failure:^(NSError *error) {
         
     }];
}

- (void)pointReportWithTocken:(NSString *)tocken pointId:(NSArray *)pointIds
{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    NSMutableString * strM = [[NSMutableString alloc] init];
    for (NSString *stationId in pointIds)
    {
        if (strM.length == 0) {
            [strM appendString:stationId];
        }else{
            [strM appendString:[NSString stringWithFormat:@",%@",stationId]];
        }
    }
    params[@"sign"] = [NSString stringWithFormat:@"{\"token\":\"%@\",\"point_id\":\"%@\"}",tocken,strM];
    
    NSString *url = @"http://120.76.154.75/app/api/car/pointReport";
    
    [IWHttpTool postWithURL:url params:params success:^(id json)
     {
//         NSDictionary *dict = json;
        
         
     } failure:^(NSError *error) {
         NSLog(@"%@",error);
         
     }];
}



@end
